package com.im.audio;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class PlayerManager {
	private final String tag = "PlayerManager";
	private MediaPlayer player = null;
	private String currentFilepath = null;

	OnCompletionListener onCompletionListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer mp) {
			player.seekTo(0);
		}
	};

	public void destory() {
		if (player == null)
			return;
		player.setOnCompletionListener(null);
		player.stop();
		player.release();
		player = null;
	}

	private void init() {

		destory();

		player = new MediaPlayer();
		player.setLooping(false);
		player.setOnCompletionListener(onCompletionListener);
	}

	public void play(String filePath) {
		if (filePath == null || filePath.trim().length() == 0) {
			return;
		}
		if (this.currentFilepath == null || filePath.equals(this.currentFilepath) == false) {
			destory();
			this.currentFilepath = filePath;
			init();
			try {
				player.setDataSource(currentFilepath);
				player.prepare();
				player.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			player.start();
		}
	}

}
